package com.haifeng.wdsh.gateway.exception;

import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.BlockRequestHandler;
import com.haifeng.wdsh.common.base.util.Rest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.ServerResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * <p>
 *  自定义限流异常处理器
 * </p>
 *
 * @author: Haifeng
 * @date: 2020-05-05
 */
@Slf4j
public class GatewayLimitBlockException implements BlockRequestHandler {

    private static final String DEFAULT_BLOCK_MESSAGE = "当前访问人数太多，请稍后再试";
    private static final String DEFAULT_BLOCK_MSG_PREFIX = "Blocked by Sentinel: ";


    @Override
    public Mono<ServerResponse> handleRequest(ServerWebExchange exchange, Throwable t) {

        return ServerResponse.status(HttpStatus.TOO_MANY_REQUESTS)
                .contentType(MediaType.APPLICATION_JSON)
                .body(BodyInserters.fromValue(buildErrorResult(t)));
    }

    private Rest buildErrorResult(Throwable ex) {
        log.error(DEFAULT_BLOCK_MSG_PREFIX + ex.getClass().getSimpleName());
        return Rest.error(HttpStatus.TOO_MANY_REQUESTS.value(),DEFAULT_BLOCK_MESSAGE);
    }
}
